package com.rimi.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author jerry
 * 用来拦截未登录的用户
 */
@WebFilter(urlPatterns = "/v2/*")
public class Filter3_LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //将用户信息存储到session中
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //从session中获取当前登录人信息
        Object user = request.getSession().getAttribute("user");
        //说明该用户没有登录
        if(user == null){
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            //跳转登录页面
            response.sendRedirect("/login.jsp");
            return;
        }
        //该用户已经登录 放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
